<template lang="pug">
.material
  .material-header
    .material-header-filter
      header-filter(:filter="filter")
    .material-header-info 设置推荐材料，需设置2~8个材料
  .material-container
    .material-table
      el-table(
        :data="list"
        style="width: 100%"
        :header-cell-style="{'fontSize': '14px', 'background': '#F7F7F7', 'color': '#363636'}"
      )
        el-table-column(label="材料名称" prop="materialName")
        el-table-column(label="分类名称" prop="category")
        el-table-column(label="品牌" prop="brandName")
        el-table-column(label="市场价")
          template(slot-scope="scope") {{scope.row.minMarketPrice === scope.row.maxMarketPrice ? '￥' + scope.row.minMarketPrice : '￥' + scope.row.minMarketPrice + '~' + scope.row.maxMarketPrice }}
        el-table-column(label="浏览量" prop="viewCount" sortable)
        el-table-column(label="上架时间" prop="shelfTime" sortable)
        el-table-column(label="推荐设置 " prop="mail")
          template(slot-scope="scope")
            el-switch(v-model="scope.row.status", :disabled="scope.row.isDisable" active-color="#8676FF" inactive-color="#B2B4C7" @change="changeStatus(scope.row)")
      .index-pagination
        .pagination-total 共 {{total}} 条
        .pagination-sizes 10 条/页
        el-pagination(
          background
          layout="prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="page"
          @current-change="currentChange"
        )
</template>

<script>
import { getAppltMaterialList, loadSupplierBrands, getMaterialCategory, setRecommendMaterial } from 'api'
import headerFilter from '@/components/headerFilter'
export default {
  name: 'appltMaterial',
  components: {
    headerFilter
  },
  data () {
    return {
      filter: [
        [
          {
            name: '材料名称：',
            type: 'default',
            key: 'searchContent',
            searchContent: '',
          },
          {
            name: '',
            type: 'select',
            key: 'brandId',
            brandId: '',
            optLabel: 'name',
            optValue: 'brandId',
            options: [],
            placeholder: '品牌选择'
          },
          {
            name: '',
            type: 'select',
            key: 'catergory',
            catergory: '',
            optLabel: 'title',
            optValue: 'id',
            options: [],
            placeholder: '材料分类'
          },
          {
            type: 'handle',
            buttons: [
              { name: 'primary', label: '查询', handle: this.search },
              { label: '重置', handle: this.reset }
            ]
          }
        ]
      ],
      total: 0,
      page: 1,
      pageSize: 10,
      list: [],
      categorys: [],
      brandList: []
    }
  },
  computed: {
    maxNum () {
      let len = this.list.filter(item => item.status).length
      if (len >= 8) {
        this.list.forEach(item => {
          if (!item.status) item.isDisable = true
          else item.isDisable = false
        })
      } else {
        this.list.forEach(item => {
          item.isDisable = false
        })
      }
      return len
    }
  },
  methods: {
    search () {
      let query = {}
      this.filter.map(row => row.map(v => {
        if (v[v.key]) query[v.key] = v[v.key]
      }))
      Object.keys(query).forEach(v => {
        if (!query[v]) delete query[v]
      })
      this.$router.replace({ name: this.$route.name, query: { ...query, tm: new Date().getTime() } })
    },
    reset () {
      this.$router.replace({ name: this.$route.name })
    },
    async initFilter () {
      try {
        await this.getBrandList()
        await this.getCategory()
        this.filter.forEach(row => row.forEach(v => {
          if (v.key === 'brandId') v.options = this.brandList
          if (v.key === 'catergory') v.options = this.categorys
          if (v.key === 'brandId' || v.key === 'catergory') {
            v[v.key] = Number(this.$route.query[v.key]) || ''
          } else {
            v[v.key] = this.$route.query[v.key] || ''
          }
        }))
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    currentChange (page) {
      this.$router.replace({ name: this.$route.name, query: { ...this.$route.query, currentPage: page, tm: new Date().getTime() } })
    },
    async changeStatus (row) {
      try {
        if (this.maxNum > 8) {
          this.$message.error('材料推荐最多设置8个！')
          return
        }
        await this.$axios.post(setRecommendMaterial, { content: { materialId: row.id } })
        this.$message.success('设置成功！')
      } catch (err) {
        row.status = !row.status
        console.log(row)
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async getBrandList () {
      try {
        const { ResultSet } = await this.$axios.post(loadSupplierBrands, { content: { reviewStatus: 2 } })
        this.brandList = ResultSet.userData.brandList
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async getCategory () {
      try {
        const { ResultSet } = await this.$axios.post(getMaterialCategory)
        this.categorys = ResultSet.userData.roots
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async getList () {
      try {
        let query = { ...this.$route.query, currentPage: this.$route.query.currentPage || 1, pageLines: this.pageSize }
        const { ResultSet } = await this.$axios.post(getAppltMaterialList, { content: { ...query } })
        let len = ResultSet.userData.materialList.filter(item => item.status).length
        if (len >= 8) {
          ResultSet.userData.materialList.forEach(item => {
            if (!item.status) item.isDisable = true
            else item.isDisable = false
          })
        }
        this.page = parseInt(this.$route.query.currentPage)
        this.list = ResultSet.userData.materialList
        this.total = typeof(ResultSet.userData.recordNumber) === 'number' || typeof(ResultSet.userData.recordNumber) === 'string' ? ResultSet.userData.recordNumber : 0
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(async vm => {
      await vm.initFilter()
      vm.getList()
    })
  },
  async beforeRouteUpdate (to, from, next) {
    next()
    await this.initFilter()
    this.getList()
  }
} 
</script>

<style lang="scss" scoped>
.material {
  padding: 0 32px 16px;
}
.material-header {
  padding: 32px 24px 16px;
  background: #FFFFFF;
  border-radius: 4px;
}
.material-header-info {
  font-size: 12px;
  line-height: 26px;
  color: #FF2E42;
  margin-top: 8px;
  padding-left: 30px;
}
.material-container {
  margin-top: 16px;
  padding: 24px;
  background: #FFFFFF;
  border-radius: 4px;
}
.material-table {
  margin-top: 16px;
}
.index-pagination {
  margin-top: 24px;
  text-align: right;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  font-size: 14px;
  color: #7A7A7A;
  .pagination-total {
    margin-right: 10px;
  }
  .pagination-sizes {
    margin-right: 10px;
  }
}
.table-item-handle {
  display: inline-block;
  padding: 0 8px;
  line-height: 1;
  cursor: pointer;
  color: #FF2E42;
  &:first-child {
    padding-left: 0;
    border-right: 1px solid #CBCBCB;
  }
}
</style>
